﻿using System;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using Ionic.Zip;

namespace PublishSoftwareWebPageCreator
{
    public partial class NewPageForm : Form
    {
        public Page page;

        public NewPageForm()
        {
            InitializeComponent();
        }

        private void bt_ok_Click(object sender, EventArgs e)
        {
            var p = takePage();
            var dir = p.takeDir();

            //检测名称是否存在
            if (Directory.Exists(dir))
            {
                lb_msg.Text = "目录已经存在";
                return;
            }
            //解压文件
            ExtractZipToDirectory(
                Assembly.GetExecutingAssembly(),
                "/PublishSoftwareWebPageCreator/page.zip",
                dir);

            this.page = p;
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        public void ExtractZipToDirectory(Assembly assembly, string zipPath, string dir)
        {
            MemoryStream zipsm;
            zipPath = zipPath.TrimStart('/').Replace("/", ".");

            using (var sm = assembly.GetManifestResourceStream(zipPath))
            {
                if (sm == null)
                {
                    throw new Exception("没有找到内嵌资源");
                }
                var data = new byte[sm.Length];
                sm.Read(data, 0, data.Length);
                zipsm = new MemoryStream(data);
            }

            if (ZipFile.IsZipFile(zipsm, false) == false)
            {
                throw new NotSupportedException("无法识别的ZIP文件");
            }

            zipsm.Position = 0;
            var _zip = ZipFile.Read(zipsm);
            _zip.ExtractAll(dir);
            //_zip.Password = pwd;
            //_pwd = pwd;
            //Domain = domain;
        }
        private bool IsLetterOrDigit(string s)
        {
            foreach (char c in s.ToCharArray())
            {
                if (!Char.IsLetterOrDigit(c)) return false;
            }
            return true;
        }

        private Page takePage()
        {
            tb_page.Text = tb_page.Text.Trim();
            tb_dir.Text = tb_dir.Text.Trim();

            if (string.IsNullOrEmpty(tb_page.Text) || string.IsNullOrEmpty(tb_dir.Text))
            {
                lb_msg.Text = "名称和目录不能为空";
                return null;
            }

            if (!IsLetterOrDigit(tb_dir.Text))
            {
                lb_msg.Text = "目录名只能是英文或数字";
                return null;
            }

            return new Page(tb_page.Text, tb_dir.Text);
        }

        private void NewPageForm_Load(object sender, EventArgs e)
        {
        }
    }
}
